package com.hmall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.service.ISerachService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hmall.common.utils.BeanUtils;

import java.io.IOException;

@Service
public class SearchServiceImpl implements ISerachService {
    //索引库名称
    private static final String INDEX_NAME = "items";

    @Autowired
    private ItemClient itemClient;

    private RestHighLevelClient client;

    public SearchServiceImpl(){
        client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.12.168:9200")));
    }
    @Override
    public void saveItemById(Long itemId) throws IOException {
        ItemDTO itemDTO = itemClient.queryItemById(itemId);
        if (itemDTO != null) {
            ItemDoc itemDoc = BeanUtils.copyBean(itemDTO, ItemDoc.class);
            String jsonStr = JSONUtil.toJsonStr(itemDoc);

            IndexRequest request = new IndexRequest(INDEX_NAME).id(itemDoc.getId().toString());
            request.source(jsonStr, XContentType.JSON);

            client.index(request, RequestOptions.DEFAULT);

        }
    }

    @Override
    public void deleteItemById(Long itemId) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME, itemId.toString());
        //2、发送请求
        client.delete(deleteRequest, RequestOptions.DEFAULT);

    }
}
